<script>
import { computed, ref, watch} from 'vue';
import decRegisterApi from '/api/dec/decUser/decRegisterApi.js';
import cryptoUtils from '/utils/CryptoJS';

// 全局状态globalData
import { storeToRefs } from "pinia";
import { useGlobalDataStore } from './globalData';

import { toByteArray } from 'base64-js';
function uint8ArrayToString(array) {
  let result = '';
  for (let i = 0; i < array.length; i++) {
    result += String.fromCharCode(array[i]);
  }
  return result;
}

export default {
  data: {
    ts: '', 			// 服务器时间戳
    RSA_KEY: '',		// RSA公钥
    device_code: '',	// 设备名称
    device_uuid: '',	// 登录设备id
    platform: '',   	// 设备平台（网页、苹果、安卓...）
    device_type: '',	// 客户端登录设备类型
  },

  methods: {
    // 获取设备信息
    async Get_system_info() {
	  // 全局状态globalData
	  const { globalData } = storeToRefs(useGlobalDataStore())
	  const { updateGlobalData } = useGlobalDataStore();

      // 获取设备信息
      return new Promise((resolve, reject) => {
        uni.getSystemInfo({
          success: (systemInfo) => {
            console.log('登录设备信息:', systemInfo);
            this.device_code = systemInfo.model;
            this.device_uuid = systemInfo.deviceId;
            this.platform = systemInfo.platform;
            // 1.windows 电脑 2.苹果电脑 3.苹果手机 4. 苹果平板 5.安卓手机 6.安卓平板  7.网页/小程序  8.其他，9-微信小程序
            if (systemInfo.platform === 'windows') {
              this.device_type = '1';
            } else if (systemInfo.platform === 'mac') {
              this.device_type = '2';
            } else if (systemInfo.platform === 'ios' && systemInfo.deviceModel.indexOf('iPhone')!== -1) {
              this.device_type = '3';
            } else if (systemInfo.platform === 'ios' && systemInfo.deviceModel.indexOf('iPad')!== -1) {
              this.device_type = '4';
            } else if (systemInfo.platform === 'android' && systemInfo.deviceModel.indexOf('Phone')!== -1) {
              this.device_type = '5';
            } else if (systemInfo.platform === 'android' && systemInfo.deviceModel.indexOf('Pad')!== -1) {
              this.device_type = '6';
            } else if (systemInfo.platform === 'h5') {
              this.device_type = '7';
            } else if (systemInfo.platform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-weixin') {
              this.device_type = '9';
            }
            else {
              this.device_type = '8';
            }
			updateGlobalData({
				...globalData.value,
				SYSTEM_INFO: {
					...globalData.value.SYSTEM_INFO,
					device_code: systemInfo.model,
					device_uuid: systemInfo.deviceId,
					platform: systemInfo.platform,
					device_type: this.device_type,
					app_version: this.appVersion
				}
			})
			// console.log("App.vue: ", globalData.value);
            resolve();
          },
          fail: (err) => {
            console.error('获取设备信息失败:', err);
            reject(err);
          }
        });
      });
    },

    // rsa公钥，主要用于注册、游客登记。此为动态密钥，更新不会太频繁。
    async Get_rsa_key() {
	  // 全局状态globalData
	  const { globalData } = storeToRefs(useGlobalDataStore())
	  const { updateGlobalData } = useGlobalDataStore();

      decRegisterApi.Get_rsa_key_API({}).then((res) => {
        // console.log('Get_rsa_key_API成功，', res)
        this.ts = res.stime
        this.RSA_KEY = uint8ArrayToString(toByteArray(res.key)) // base64解码
		updateGlobalData({
			...globalData.value,
			ENCRYPTED_PWD_INFO: {
				...globalData.value.ENCRYPTED_PWD_INFO,
				RSA_KEY: this.RSA_KEY
			}
		});

      }).catch((err) => {
        console.error('Get_rsa_key_API失败，', err)
      });
    },

    // 未注册访客登记，用于处理未注册用户在系统中的临时登记操作
    async Unregistered_tourists() {
	  // 全局状态globalData
	  const { globalData } = storeToRefs(useGlobalDataStore())
	  const { updateGlobalData } = useGlobalDataStore();

      while (!this.device_type || !this.ts || !this.RSA_KEY || !this.device_code || !this.device_uuid) {
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
      let timestamp = Date.now().toString();
      let MD5timestamp = cryptoUtils.MD5Encrypt(timestamp);
      let RSAEncryptedMD5timestamp = cryptoUtils.RSAEncrypt(MD5timestamp, this.RSA_KEY);

      let params = {
        device_type: this.device_type,
        device_code: this.device_code,
        device_uuid: this.device_uuid,
        ts: this.ts,
        aes_key: RSAEncryptedMD5timestamp,
      };
	  // 这里必须加上return, 否则导致外部后续代码先执行
      return decRegisterApi.Unregistered_tourists_API(params).then((res) => {
        // console.log('Unregistered_tourists_API成功，', res);
        const resDatas = res.datas;
        const key = MD5timestamp.slice(0,16);
        const iv = MD5timestamp.slice(-16);
        const DecryptDatas = cryptoUtils.AES_Decrypt(resDatas, key, iv);

        const visitData =  JSON.parse(DecryptDatas);
		updateGlobalData({
			...globalData.value,
			VISIT_DATA: {
				...globalData.value.VISIT_DATA,
				visit_id: visitData.id,
				visit_key: visitData.login_sign_key,
				visit_str: visitData.login_str
			}
		});

        // this.globalData.VISIT_DATA.id = visitData.id;
        // this.globalData.VISIT_DATA.login_sign_key = visitData.login_sign_key;
        // this.globalData.VISIT_DATA.login_str = visitData.login_str;
        // console.log("VISIT_DATA: ", this.globalData.VISIT_DATA);
        // console.log("login_sign_key",visitData.login_sign_key);
		updateGlobalData({
			...globalData.value,
			ENCRYPTED_PWD_INFO: {
				...globalData.value.ENCRYPTED_PWD_INFO,
				AES_KEY: visitData.login_sign_key.slice(0,16),
				AES_IV: visitData.login_sign_key.slice(-16)
			}
		});

      }).catch((err) => {
        console.error('Unregistered_tourists_API失败，', err);
      })
    },
  },

  onLaunch: async function() {
    const systemInfoPromise = this.Get_system_info();
    const rsaKeyPromise = this.Get_rsa_key();
    await Promise.all([systemInfoPromise, rsaKeyPromise]);
    await this.Unregistered_tourists();

	// 全局状态globalData
	const { globalData } = storeToRefs(useGlobalDataStore())
	// console.log("app.vue出口globalData: ", globalData.value);
  },

  onShow: function() {},
  onHide: function() {}
}
</script>


<style lang="scss">
@import "styles/public.scss";
// /*每个页面公共css */
// /* 微信小程序将page设置为高度100% */
// #ifdef MP-WEIXIN
page{
  height: 100%;
}

// #endif

uni-page-body{
  height: auto;
}
</style>

<style>
@import "/wxcomponents/vant/common/index.wxss";
</style>
